package com.example.client;

import com.example.constant.MessageType;
import com.example.pojo.Header;
import com.example.pojo.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/30 21:58
 */
public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(LoginAuthReqHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(this.buildLoginReq());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 如果是握手应答消息，需要判断是否认证成功
        final NettyMessage message = (NettyMessage) msg;
        if (message.getHeader() != null
                && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
            if ((byte) message.getBody() != 0) {
                ctx.close();
            } else {
                log.info("Login is ok : {}", message);
                ctx.fireChannelRead(msg);
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("error=", cause);
        ctx.fireExceptionCaught(cause);
    }

    private NettyMessage buildLoginReq() {
        final Header header = new Header();
        header.setType(MessageType.LOGIN_REQ.value());

        final NettyMessage message = new NettyMessage();
        message.setHeader(header);
        return message;
    }

}